<template>
  <el-card class="box-card">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索 -->
    <el-row class="SearchRow">
      <el-col>
        <el-input placeholder="请输入内容"
                  @clear="loadUserList()"
                  clearable
                  width="100px"
                  v-model="query"
                  class="inputSearch">
          <el-button slot="append"
                     @click="searchUser()"
                     icon="el-icon-search"></el-button>
        </el-input>
        <el-button type="success"
                   @click="showAddUserDia()">添加</el-button>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <el-table :data="tableData"
              style="width: 100%">
      <el-table-column type="index"
                       label="#"
                       width="60">
      </el-table-column>
      <el-table-column prop="username"
                       label="姓名"
                       width="80">
      </el-table-column>
      <el-table-column prop="email"
                       label="邮箱">
      </el-table-column>
      <el-table-column label="创建日期">
        <template slot-scope="scope">
          {{scope.row.date | fmtdate}}
        </template>
      </el-table-column>
      <el-table-column label="用户状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status"
                     @change="changeStatus(scope.row)"
                     active-color="#13ce66"
                     inactive-color="#ff4949">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary"
                     size="mini"
                     plain
                     icon="el-icon-edit"
                     @click="showEditUserDia(scope.row)"
                     circle></el-button>
          <el-button type="danger"
                     size="mini"
                     plain
                     @click="showDelUserMsgBox(scope.row.id)"
                     icon="el-icon-delete"
                     circle></el-button>
          <el-button type="success"
                     size="mini"
                     plain
                     icon="el-icon-check"
                     @click="showSetUserRoleDia(scope.row)"
                     circle></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   :current-page="pagenum"
                   :page-sizes="[2, 3, 4, 5]"
                   :page-size="2"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="total">
    </el-pagination>

    <!-- 对话框 -->

    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户"
               :visible.sync="dialogFormVisibleAdd">
      <el-form :model="form">
        <el-form-item label="用户名"
                      :label-width="formLabelWidth">
          <el-input v-model="form.username"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码"
                      :label-width="formLabelWidth">
          <el-input v-model="form.password"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱"
                      :label-width="formLabelWidth">
          <el-input v-model="form.email"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话"
                      :label-width="formLabelWidth">
          <el-input v-model="form.mobile"
                    autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogFormVisibleAdd = false">取 消</el-button>
        <el-button type="primary"
                   @click="addUser()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog title="编辑用户"
               :visible.sync="dialogFormVisibleEdit">
      <el-form :model="form">
        <el-form-item label="用户名"
                      :label-width="formLabelWidth">
          <el-input v-model="form.username"
                    disabled
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱"
                      :label-width="formLabelWidth">
          <el-input v-model="form.email"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话"
                      :label-width="formLabelWidth">
          <el-input v-model="form.mobile"
                    autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogFormVisibleEdit = false">取 消</el-button>
        <el-button type="primary"
                   @click="editUser()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 设置角色对话框 -->
    <el-dialog title="分配角色"
               :visible.sync="dialogFormVisibleRol">
      <el-form :model="form">
        <el-form-item label="用户名"
                      :label-width="formLabelWidth">
          {{currUserName}}
        </el-form-item>
        <el-form-item label="角色"
                      :label-width="formLabelWidth">
          <el-select v-model="currRoleId">
            <el-option label="请选择"
                       disabled
                       :value="-1"></el-option>
            <el-option :label="item.rolename"
                       :value="item.roleid"
                       v-for="(item,index) in rolelist"
                       :key="item.roleid"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="setRole()">确 定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
export default {
  data() {
    return {
      query: '',
      pagenum: 1,
      pagesize: 2,
      tableData: [],
      total: 1,
      // 添加对话框的属性
      dialogFormVisibleAdd: false,
      dialogFormVisibleEdit: false,
      dialogFormVisibleRol: false,
      //添加用户的表单数据
      form: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      // 分配角色
      currRoleId: -1,
      currUserName: '',
      currUserId: '',
      rolelist: [],
      //对话框宽度
      formLabelWidth: '100px',
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    // 设置角色
    async setRole() {
      const res = await this.$http.put('setRole/${this.currUserId}/role', {
        rid: this.currRoleId,
      });
      console.log(res);
      this.$message.success(res.data.msg);
      this.dialogFormVisibleRol = false;
    },
    // 实现更改用户角色弹框
    async showSetUserRoleDia(user) {
      this.currUserName = user.username;
      // 给当前用户id赋值,在分配对象时用
      this.currUserId = user.userId;
      // 获取当前用户角色id
      const res = await this.$http.get('getRoleId/${user.id}');
      console.log(res);
      this.rolelist = res.data.rolelist;
      // 获取当前用户角色,然后将当前用户角色给v-model绑定
      //  this.currRoleId=res.data.data.currRoleId;
      this.currRoleId = 1;
      this.dialogFormVisibleRol = true;
    },
    // 更改用户状态 --> 发送请求
    async changeStatus(user) {
      const res = await this.$http.put(
        'changeStatus/${user.id}/status/${user.status}',
      );
      console.log(res);
    },
    // 编辑用户 --> 发送请求
    async editUser() {
      // 因为在这个弹出框中没有scope的数据，所以数据传不进来，因此我们要在data中声明数据
      const res = await this.$http.put('/editUser/${this.form.id}', this.form);
      // 关闭对话框
      this.dialogFormVisibleEdit = false;
      // 更新视图
      this.getUserList();
      console.log('修改成功！');
      console.log(res);
    },
    // 编辑用户，打开对话框
    showEditUserDia(user) {
      // 获取用户数据
      this.form = user;
      this.dialogFormVisibleEdit = true;
    },
    // 删除用户，打开消息弹窗
    showDelUserMsgBox(userId) {
      this.$confirm('删除用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          //发送删除请求  根据id删除
          const res = await this.$http.delete('delUserById/${userId}');
          console.log(res);
          this.$message.success(res.data.msg);
          // const {
          //   data: { msg, statusCode },
          // } = res;
          // if (statusCode == 200) {
          //   //   删除完回到首页
          //   pagenum = 1;
          //   // 更新视图
          //   this.getUserList();
          //   // 提示
          //   this.$message({
          //     type: 'success',
          //     message: msg,
          //   });
          // }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },
    // 添加用户——发送请求
    async addUser() {
      // 关闭对话框
      this.dialogFormVisibleAdd = false;
      const res = await this.$http.post('userAdd', this.form);
      console.log(res);
      const {
        data: { msg, statusCode },
      } = res;
      if (statusCode === '201') {
        // 提示成功，关闭对话框
        this.$message.success(msg);

        // 重新渲染数据，更新视图
        this.getUserList();
        // 清空文本狂
        // this.form = {};
        // 遍历清空
        // for (const key in this.form) {
        //   if (this.form.hasOwnProperty(key)) {
        //     this.form[key] = ' ';
        //   }
        // }
      }
    },
    // 展示添加用户对话框
    showAddUserDia() {
      this.form = {};
      this.dialogFormVisibleAdd = true;
    },
    // 清空搜索框 重新获取数据
    loadUserList() {
      this.getUserList();
    },
    // 搜索用户
    searchUser() {
      this.getUserList();
    },
    // 分页相关方法
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pagesize = val;
      this.getUserList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pagenum = val;
      this.getUserList();
    },
    //获取用户列表请求
    async getUserList() {
      // 在访问时要设置请求头，在请求头中使用Authorization字段提供token令牌 (原生ajax 和jquery ajax都能设置请求头)
      // 我们这里用的是axios，所以要设置请求头我们在axios文档，如果用的是jquery ajax，要找jquery ajax能不能设置请求头
      // const AUTH_TOKEN = localStorage.getItem('token');
      // this.$http.defaults.headers.common['Authorization'] = AUTH_TOKEN;

      const res = await this.$http.get(
        'users?query=${this.query}&pagenum=${this.pagenum}&pagesize=${pagesize}',
      );
      console.log(res);
      //   this.tableData = res.data.users;
      const {
        status,
        data: { users, total },
      } = res;

      if (status === 200) {
        // 给表格数据赋值
        this.tableData = users;
        // 给total赋值
        this.total = total;
        // 提示用户
        this.$message.success('查询成功');
      }
    },
  },
};
</script>

<style scoped>
.box-card {
  height: 100%;
}
.inputSearch {
  width: 300px;
}
.SearchRow {
  margin-top: 20px;
}
</style>